import axios from 'axios';

// action type
const AUTH_SUCCESS = 'AUTH_SUCCESS';
const LOGOUT = 'LOGOUT';
const LOAD_DATA = 'LOAD_DATA';
const ERROR_MSG = 'ERROR_MSG';

// initial state
const initState = {
	redirectTo: '',
	msg: '',
	logged: false
};

// reducer
export function user(state=initState, action) {
	switch (action.type) {
		case AUTH_SUCCESS: 
			return {...state, redirectTo: '/', logged: true, msg: '', ...action.payload};
		case LOAD_DATA:
			return {...state, logged: true, ...action.payload};
		case ERROR_MSG: 
			return {...state, msg: action.msg, logged: false};
		case LOGOUT: 
			return {...state, redirectTo: '/', logged: false};
		default: 
			return {};
	}
}

// action creator
function auth(obj) {
	// 过滤密码
	const { password, confirm, ...data } = obj;
	return {type: AUTH_SUCCESS, payload: data};
}
function error(msg) {
	return {msg, type: ERROR_MSG};
}

// 获取用户信息
function loadData(data) {
	return {type: 'LOAD_DATA', payload: data};
}

// 退出
function logoutSubmit() {
	return {type: LOGOUT};
}

// 注册
export function register(obj) {
	// 异步
	return dispatch => {
		axios.post('/user/register', obj)
			.then(res => {
				if (res.status === 200 && res.data.code === 0) {
					dispatch(auth(res.data.data));
				}else {
					dispatch(error(res.data.msg));
				}
			})
			.catch(err => {
				console.log('请求错误信息',err);
			})
	}
}

// 登录
export function login(obj) {
	// 异步
	return (dispatch, getState) => {
		axios.post('/user/login', obj)
			.then(res => {
				if (res.status === 200 && res.data.code === 0) {
					  dispatch(auth(obj));
				}else {
					return dispatch(error(res.data.msg));
				}			
			})
			.catch(err => {
				console.log('请求错误信息',err);
			})
	}
}
// 获取用户信息
export function getUserinfo() {
	return dispatch => {
		axios.get('/user/info')
			.then(res => {
				if (res.status === 200 && res.data.code === 0) {
					return dispatch(loadData(res.data.data));
				}
				return dispatch(error(res.data.msg));
			})
	}
}

// 退出
export function logout() {
	return dispatch => {
		axios.get('/logout')
			.then(res => {
				if (res.status === 200 && res.data.code === 1) {
					return dispatch(logoutSubmit(res.data.data));
				}
				return dispatch(error(res.data.msg));
			})
	}

}

